package com.zd.kids.net;

import com.blankj.utilcode.util.SPUtils;
import com.hyy.language.CommonUtils;
import com.hyy.libray.common.Constant;
import com.zd.kids.BuildConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class CustomApi {

    private int DEFAULT_TIMEOUT = 15000;

    private int DEFAULT_SMALL_TIMEOUT = 1500;

    private ApiService mApiService;

    private Retrofit mRetrofit;

    public static boolean isSmalllTimeOut;

    private CustomApi() {

        Interceptor interceptor = chain -> {
            Request request = chain.request().newBuilder()
                    //添加cookie
                    .addHeader("jwt", SPUtils.getInstance(Constant.GAPSK_AI_QM).getString("jwt"))
                    .addHeader("Accept-Language", CommonUtils.getCurLanguage())
                    .build();
            return chain.proceed(request);
        };

        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();//Https请求认证
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .addInterceptor(interceptor);

        if (BuildConfig.DEBUG) {
            builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        }
        OkHttpClient okHttpClient = builder.build();

        mRetrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(BuildConfig.DEBUG ? Constant.TEST_BASE_URL : Constant.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();


        mApiService = mRetrofit.create(ApiService.class);

    }


    private static CustomApi mCustomApi;

    public static CustomApi getIntence() {
        if (mCustomApi == null) {
            synchronized (CustomApi.class) {
                if (mCustomApi == null) {
                    mCustomApi = new CustomApi();
                }

            }
        }

        return mCustomApi;
    }


    public ApiService getApi() {
        if (mApiService == null) {
        } else {
        }
        return mApiService;
    }
}
